<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm v-if="$access('ENT_UR_USER_SEARCH')" :searchFunc="searchFunc" :resetFunc="() => { vdata.searchData= {} }">
        <jeepay-text-up v-model:value="vdata.searchData['sysUserId']" :placeholder="'用户ID'" />
        <jeepay-text-up v-model:value="vdata.searchData['realname']" :placeholder="'用户姓名'" />
        <jeepay-text-up v-model:value="vdata.searchData['telphone']" :placeholder="'用户手机号'" />
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="sysUserId"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #topBtnSlot>
          <div>
            <a-button v-if="$access('ENT_UR_USER_ADD')" type="primary" class="mg-b-30" @click="addFunc"><plus-outlined />新建</a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar size="default" :src="record.avatarUrl" />
          </template>
          <template v-if="column.key === 'realname'">
            {{ record.realname }}
            <a-tag v-if="record.initUser" :key="record.initUser" color="green">
              初始
            </a-tag>
          </template>
          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state" :showSwitchType="$access('ENT_UR_USER_EDIT')" :onChange="(state) => { return updateState(record.sysUserId, state)}" />
          </template>
          <template v-if="column.key == 'sex'">
            {{ record.sex === 1 ? '男' : record.sex === 2 ? '女' : '未知' }}
          </template>
          <template v-if="column.key === 'userType'">
            <span v-if="record.userType == 1">超级管理员</span>
            <span v-else-if="record.userType == 2">普通操作员</span>
            <span v-else-if="record.userType == 11">店长</span>
            <span v-else-if="record.userType == 12">店员</span>
            <span v-else>其他</span>
          </template>
          
          <template v-if="column.key === 'op'">
            <JeepayTableColumns>
              <!-- 操作列插槽 -->
              <a-button v-if="$access('ENT_UR_USER_EDIT')" type="link" style="padding-right: 10px;padding-left: 10px;" @click="editFunc(record.sysUserId)">修改</a-button>
              <a-button v-if="$access('ENT_UR_USER_UPD_ROLE') && record.userType == '2'" type="link" @click="roleDistFun(record.sysUserId)">变更角色</a-button>
              <a-button v-if="$access('ENT_UR_USER_MFA_DELETE') && (userStore.userInfo['userType'] == '1' && record.mfaBindState == '1')" style="color: red;" type="link" @click="mfaRelieve(record.sysUserId)">MFA解绑</a-button>
              <a-button v-if="$access('ENT_UR_USER_LOGIN_LIMIT_DELETE')" style="color: red;" type="link" @click="deleteLoginLimit(record.sysUserId)">解除登录限制</a-button>
              <a-button v-if="$access('ENT_UR_USER_DELETE')" type="link" style="color: red" @click="delFunc(record.sysUserId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <!-- 新增 / 修改 页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callbackFunc="searchFunc" />

    <InfoBindStore ref="infoBindStore" :callbackFunc="searchFunc" />

    <!-- 分配角色 页面组件  -->
    <RoleDist ref="roleDist" />
  </page-header-wrapper>
</template>
<script lang="ts" setup>
import { API_URL_SYS_USER_LIST, req, reqLoad, $deleteLoginLimit } from '@/api/manage'
import { useUserStore } from '@/store/modules/user'
import InfoAddOrEdit from './AddOrEdit.vue'
import InfoBindStore from './BindStore.vue'
import RoleDist from './RoleDist.vue'
import {ref, onMounted, reactive, getCurrentInstance} from 'vue'
// 获取全局函数
const { $infoBox,$access } = getCurrentInstance()!.appContext.config.globalProperties
const userStore = useUserStore()

const tableColumns = reactive([
  {key:'avatar',title: '头像',},
  {key:'realname', title: '姓名', dataIndex: 'realname' },
  {key:'sysUserId', title: '用户ID', dataIndex: 'sysUserId',},
  {key:'sex', title: '性别', dataIndex: 'sex',},
  {key:'userNo', title: '编号', dataIndex: 'userNo', },
  {key:'telphone', title: '手机号', dataIndex: 'telphone',},
  {key:'userType' ,title: '操作员类型', dataIndex: 'userType',},
  {key:'state', title: '状态', align: 'center' ,},
  {key:'createdAt', title: '创建时间', dataIndex: 'createdAt',},
  {key: 'op',title: '操作',  fixed: 'right',align: 'center' }
])
  const roleDist = ref()
  const infoAddOrEdit  =ref()
  const infoBindStore  =ref()
  const infoTable =ref()
  const vdata = reactive({
    tableColumns: tableColumns,
    searchData: {},
    btnLoading: false
  })

    // 请求table接口数据
  function reqTableDataFunc (params)  {
    return req.list(API_URL_SYS_USER_LIST, params)
  }
  function searchFunc() { // 点击【查询】按钮点击事件
    vdata.btnLoading = true // 打开查询按钮的loading
    infoTable.value.refTable(true)
  }
  function  addFunc () { // 业务通用【新增】 函数
    infoAddOrEdit.value.show()
  }
  function  delFunc (recordId) { // 业务通用【删除】 函数
    
    $infoBox.confirmDanger('确认删除？', '', () => {
      return req.delById(API_URL_SYS_USER_LIST, recordId).then(res => {
        $infoBox.message.success('删除成功！')
        infoTable.value.refTable(false)
      })
    })
  }
  function  editFunc (recordId) { // 业务通用【修改】 函数
    infoAddOrEdit.value.show(recordId)
  }
  function bindStoreFunc(recordId, userType) {
    infoBindStore.value.show(recordId, userType)
  }
  function  roleDistFun(recordId) { // 【分配权限】 按钮点击事件
    roleDist.value.show(recordId)
  }
  function  updateState (recordId, state) { // 【更新状态】 
    const title = state === 1 ? '确认[启用]该用户？' : '确认[停用]该用户？'
    const content = state === 1 ? '启用后用户可进行登陆等一系列操作' : '停用后该用户将立即退出系统并不可再次登陆'
    return new Promise<void>((resolve, reject) => {
      $infoBox.confirmDanger(title, content, () => {
        return reqLoad.updateById(API_URL_SYS_USER_LIST, recordId, { state: state }).then(res => {
          searchFunc()
          resolve()
        }).catch(err => reject(err))
      },
        () => {
        reject(new Error())
      })
    })
  }

  function mfaRelieve(recordId) { // MFA解绑
    $infoBox.confirmDanger('确认解绑吗？', '', () => {
      return req.updateById(API_URL_SYS_USER_LIST, 'mfaRelieve', {recordId: recordId}).then(res => {
        $infoBox.message.success('解绑成功！')
        infoTable.value.refTable(false)
      })
    })
  }

  function deleteLoginLimit(recordId) { // 解除登录限制
    $infoBox.confirmDanger('确认解除吗？', '', () => {
      return $deleteLoginLimit(recordId).then(res => {
        $infoBox.message.success('解除成功！')
        infoTable.value.refTable(false)
      })
    })
  }

</script>
